<?php

namespace app\user\controller\user;

use app\admin\logic\ImportQuestionLogic;
use app\common\controller\Userend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 我的课程
 *
 * @icon fa fa-circle-o
 */
class Course extends Userend
{

    /**
     * 模型对象
     * @var \app\common\model\Course
     */
    protected $model = null;

    /**
     * 是否开启数据限制
     * 支持auth/personal
     * 表示按权限判断/仅限个人
     * 默认为禁用,若启用请务必保证表中存在user_id字段
     */
    protected $dataLimit = true;

    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'name';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Course;
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }

                    // 检查课程总数
                    $count = $this->model->where(['user_id' => $this->auth->id])->count();
                    if ($count >= 10) {
                        $this->error(__('普通用户最多创建10套题库'));
                    }

                    // 填充信息
                    $params['exam_id'] = 0;
                    $params['extend_id'] = 0;
                    $params['question_algorithm'] = 0;
                    $params['type'] = 1;
                    $params['a_time'] = time();
                    $params['u_time'] = time();
                    $result = $this->model->allowField(true)->save($params);

                    // 充值课程
                    $model = new \app\admin\model\user\Course();
                    $model->setExpire($this->auth->id, $this->model->id, time() + 86400 * 365 * 10);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $params['u_time'] = time();
                    $result = $row->allowField(true)->save($params);

                    // 课程充值
                    $model = new \app\admin\model\user\Course();
                    $model->setExpire($row['user_id'], $row['id'], time() + 86400 * 365 * 10);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 导入题目
     * @param $ids
     * @return string
     * @throws \think\Exception
     */
    public function importquestion($ids = null)
    {
        if ($this->request->isPost()) {
            // 请求参数
            $params = $this->request->post("row/a");
            if (!$params) {
                $this->error(__('请求参数不得为空'));
            }
            if (empty($params['course_id'])) {
                $this->error(__('导入课程不得为空'));
            }
            if (empty($params['attachment'])) {
                $this->error(__('请求文件不得为空'));
            }
            // 检查选择保存目录
            $save_directory = $params['save_directory'] ?? 0;
            $extend_id = $params['extend_id'] ?? 0;
            if ($save_directory != 0) {
                if ($save_directory == 3 && !$extend_id) {
                    $this->error(__('请选择保存的章节目录'));
                }
                if ($save_directory == 4 && !$extend_id) {
                    $this->error(__('请选择保存的真题目录'));
                }
                if ($save_directory < 3) {
                    $extend_id = 0;
                }
            }

            try {
                Db::startTrans();
                (new ImportQuestionLogic())->import($params['course_id'], $save_directory, $extend_id, $params['attachment']);
                Db::commit();
            } catch (\Exception $exception) {
                Db::rollback();
                $this->error(__($exception->getMessage()));
            }
            $this->success('导入成功');
        }
        $this->assign('ids', $ids);
        return $this->view->fetch();
    }

    /**
     * 扫码练习
     */
    public function qrcode($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $params['u_time'] = time();
                    $result = $row->allowField(true)->save($params);

                    // 课程充值
                    $model = new \app\admin\model\user\Course();
                    $model->setExpire($row['user_id'], $row['id'], time() + 86400 * 365 * 10);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
